import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;


/**
 * Logs the uptime for a peer
 * @author Lasse
 * @param <RadioPeer>
 *
 */
public class Graph {
	
	private FileOutputStream fileOutputStream;
	private PrintWriter printWriter;
	private Calendar currentDate;
	private SimpleDateFormat formatter;
	private static final DateFormat df = new SimpleDateFormat("ddMMyyyyhhmmss");
	private List<RadioPeer.Peer> peers;
	private RadioPeer.Peer peer;
	private String graph;
	/**
	 * @param <RadioPeer>
	 * 
	 */
	public Graph(List<RadioPeer.Peer> peers) {
		this.peers = peers;
		graph = "graph network {\n";
		
		// First list all peers
		for (int i = 0;  i<peers.size(); i++) {
			peer = peers.get(i);
			graph += "\"P" + peer.getPort() + "(" + peer.getCapacity() + ")\"\n";
		}
		
		// Second print their relationships
		for (int i = 0;  i<peers.size(); i++) {
			peer = peers.get(i);
			if(peer.getChildren().size() > 0){
				for (RadioPeer.Peer child : peer.getChildren()) {
					graph += "\"P" + peer.getPort() + "(" + peer.getCapacity() + ")\" -- \"P"+ child.getPort()
							+"("+child.getCapacity() + ")\"\n";
				}
			}	
		}
		graph = graph + "}";
	}
	
	/**
	 * Outputs the graph to system.out
	 */
	public void printGraph() {
		System.out.println(graph);
	}
	
	/**
	 * Outputs the graph in i .dot file
	 */
	public void saveGraph() {
		currentDate = Calendar.getInstance();
		String filename = "graph_" + df.format(currentDate.getTime()) + ".dot";
		
		try {
			// initialize the file 
			BufferedWriter out = new BufferedWriter(new FileWriter(filename));
			out.write(graph);
			out.flush();
			out.close();
		}
		catch (Exception e) {
			System.out.print(e);
		}
	}
}
